import BafModal from '@/components/baf-modal.vue';
import { ElButton } from 'element-plus';
import { ref, h, createApp } from 'vue';
export function useDialog(component, props, modalProps) {
  const visible = ref(true);
  const instance = ref();
  const loading = ref(false);
  const dialog = () => {
    h(
      BafModal,
      {
        ...modalProps,
        modelValue: visible.value,
        onClose() {
          app.unmount();
          document.body.removeChild(div);
        }
      },
      {
        default: () => h(component, { ...props, ref: instance }),
        footer: () => {
          return h(
            'div',
            {
              class: 'baf-modal-footer'
            },
            [
              h(
                ElButton,
                {
                  type: 'default',
                  onClick: cancel
                },
                () => '取消'
              ),
              h(
                ElButton,
                { type: 'primary', onClick: submit, loading: loading.value },
                () => '确 认'
              )
            ]
          );
        }
      }
    );
  };

  const app = createApp(dialog);
  const div = document.createElement('div');
  document.body.appendChild(div);
  app.mount(div);
  async function submit() {
    loading.value = true;
    try {
      await instance.value?.submit?.();
      visible.value = false;
    } finally {
      loading.value = false;
    }
  }
  function cancel() {
    visible.value = false;
  }
}
